import { PageContainer, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Form,
  Upload,
  Space,
  Select,
  Avatar,
  Image,
  InputNumber,
} from "antd";
import { connect } from "umi";
import { DeleteOutlined, PlusOutlined, UserOutlined } from "@ant-design/icons";

import { namespace, calcColumns } from "./configFile";
import { useEffect, useRef, useState } from "react";
import UploadPreview from "@/components/UploadPreview";
import styles from "./styles.less";
const Page = (props) => {
  const { dispatch, submitLoading, venueArr } = props;
  const [open, setOpen] = useState(false);
  const [visible, setVisible] = useState(false);
  const [type, setType] = useState("课程");
  const [form] = Form.useForm();
  const [titleType, setTitleType] = useState(0);
  const [bannerUrl, setBannerUrl] = useState("");
  const actionRef = useRef();
  const actionRef2 = useRef();

  // useEffect(() => {
  //   dispatch({
  //     type: `${namespace}/pageInit`,
  //   });
  // }, []);

  const editInfo = (params) => {
    setTitleType(1);
    form.setFieldsValue({
      ...params,
      displayDrawUrl: params.displayDrawUrl,
    });
    setBannerUrl(params.displayDrawUrl);
    setOpen(true);
  };

  const toggleState = (params) => {
    dispatch({
      type: `${namespace}/toggleState`,
      params,
      callback: (res) => {
        actionRef.current?.reload();
      },
    });
  };

  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    hideInSearch: true,
    render: (_, record) => {
      const _status = parseInt(record.status, 10);
      return (
        <Space>
          <Button type="link" onClick={() => editInfo(record)}>
            编辑
          </Button>
          {_status === 0 ? (
            <Button
              type="link"
              danger
              onClick={() =>
                toggleState({
                  ...record,
                  status: "1",
                })
              }
            >
              下架
            </Button>
          ) : (
            <Button
              type="link"
              onClick={() =>
                toggleState({
                  ...record,
                  status: "0",
                })
              }
            >
              上架
            </Button>
          )}
        </Space>
      );
    },
  };

  const submitForm = async () => {
    const res = await form.validateFields();
    if (res) {
      dispatch({
        type: `${namespace}/submitItem`,
        params: {
          ...res,
          displayDrawUrl: bannerUrl,
          pointType: 3,
          displaySort: res.displaySort ? res.displaySort : 0,
        },
        callback: () => {
          form.resetFields();
          setOpen(false);
          actionRef.current?.reload();
        },
      });
    }
  };

  return (
    <PageContainer>
      <ProTable
        scroll={{ x: 1500 }}
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setTitleType(0);
              form.resetFields();
              setOpen(true);
              setBannerUrl("");
            }}
          >
            新增
          </Button>,
        ]}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        pagination={{
          showSizeChanger: true,
        }}
        columns={calcColumns({ operate, venueArr })}
      />

      <Modal
        open={open}
        title={titleType ? "编辑首页弹窗" : "新建首页弹窗"}
        width={800}
        forceRender
        onCancel={() => {
          form.resetFields();
          setOpen(!open);
        }}
        footer={
          <Space>
            <Button
              onClick={() => {
                form.resetFields();
                setOpen(false);
              }}
            >
              取消
            </Button>
            <Button onClick={submitForm} loading={submitLoading} type="primary">
              确定
            </Button>
          </Space>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ displaySort: 0 }}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            label="Banner名称"
            name="popupName"
            rules={[{ required: true, message: "Banner名称不能为空" }]}
          >
            <Input maxLength={12} placeholder="请输入,限制12个字" showCount />
          </Form.Item>

          {/* <Form.Item
            label="所属场馆"
            name="venueId"
            rules={[{ required: true, message: "请选择所属场馆" }]}
          >
            <Select
              placeholder="请选择"
              onChange={(val) => {
                form.resetFields(["pointType"]);
              }}
            >
              {venueArr.map((v) => (
                <Select.Option value={v.id}>{v.venueName}</Select.Option>
              ))}
            </Select>
          </Form.Item> */}

          <Form.Item
            label="宣传图"
            name="displayDrawUrl"
            rules={[{ required: true, message: "请上传宣传图" }]}
          >
            {bannerUrl ? (
              <div className={styles.avatar_box}>
                <Image width={334} height={160} src={bannerUrl} />
                <a
                  onClick={() => {
                    form.setFieldsValue({ displayDrawUrl: "" });
                    setBannerUrl("");
                  }}
                >
                  <DeleteOutlined
                    style={{ fontSize: "15px", color: "#ffffff" }}
                  />
                </a>
              </div>
            ) : (
              <UploadPreview
                aspect={668 / 320}
                onSuccess={(e) => {
                  form.setFieldsValue({ displayDrawUrl: e });
                  setBannerUrl(e);
                }}
              />
            )}
          </Form.Item>

          {/* <Form.Item
            label="指向类型"
            name="pointType"
            rules={[{ required: true, message: "指向类型不能为空" }]}
          >
            <Radio.Group
              onChange={(e) => {
                if (e.target.value !== "3") {
                  const venueId = form.getFieldValue("venueId");
                  if (!venueId) {
                    form.validateFields(["venueId"]);
                    form.resetFields(["pointType"]);
                  } else {
                    setVisible(true);
                    setType(e.target.value);
                    actionRef2.current?.reload();
                  }
                }
              }}
            >
              <Radio value="1">课程</Radio>
              <Radio value="2">教练</Radio>
              <Radio value="3">自定义页面</Radio>
            </Radio.Group>
          </Form.Item> */}
          <Form.Item
            label="指向链接"
            name="pointUrl"
            rules={[{ required: false, message: "请输入指向链接" }]}
          >
            <Input placeholder="请输入指向链接" />
          </Form.Item>

          <Form.Item label="显示顺序" name="displaySort">
            <InputNumber
              min={0}
              max={10000}
              precision={0}
              controls={false}
              style={{ width: "100%" }}
              placeholder="请输入显示顺序,输入的值越大，展示越靠前"
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        open={visible}
        title={type === "1" ? "课程" : "教练"}
        forceRender
        width={"80%"}
        onCancel={() => {
          setVisible(false);
        }}
        footer={
          <Space>
            <Button
              onClick={() => {
                form.resetFields(["pointType"]);
                setVisible(false);
              }}
            >
              取消
            </Button>
            <Button
              onClick={() => {
                setVisible(false);
              }}
              loading={submitLoading}
              type="primary"
            >
              确定
            </Button>
          </Space>
        }
      >
        <ProTable
          search={{
            defaultCollapsed: true,
          }}
          scroll={{ x: 1500, y: 200 }}
          actionRef={actionRef2}
          request={async (params) => {
            //const venueId = form.getFieldValue("venueId");
            return await dispatch({
              type: `${namespace}/queryCoachOrCourse`,
              params: {
                ...params,
              },
              queryType: type,
            });
          }}
          pagination={{
            showSizeChanger: true,
          }}
          columns={
            type === "1"
              ? [
                  { title: `课程ID`, dataIndex: "id", hideInSearch: true },
                  { title: "课程名称", dataIndex: "courseName" },
                  {
                    title: "课程类型",
                    dataIndex: "courseType",
                    hideInSearch: true,
                    valueEnum: {
                      1: { text: "私教课" },
                      2: { text: "团课" },
                      3: { text: "班课" },
                    },
                  },
                  {
                    title: "教练",
                    dataIndex: "courseCoachName",
                    hideInSearch: true,
                  },
                  { title: "头像", dataIndex: "avater", hideInSearch: true },
                  {
                    title: "操作",
                    fixed: "right",
                    dataIndex: "operate",
                    hideInSearch: true,
                    render: (_, row) => (
                      <Button
                        type="link"
                        onClick={() => {
                          form.setFieldValue(
                            "pointUrl",
                            row.id + "-" + row.courseName
                          );
                          setVisible(false);
                        }}
                      >
                        选择
                      </Button>
                    ),
                  },
                ]
              : [
                  { title: `教练ID`, dataIndex: "userId", hideInSearch: true },
                  { title: "教练", dataIndex: "nickName" },
                  {
                    title: "头像",
                    dataIndex: "avatar",
                    hideInSearch: true,
                    render: (_, record) => {
                      let { avatar } = record;
                      return <Avatar icon={<UserOutlined />} src={avatar} />;
                    },
                  },
                  {
                    title: "操作",
                    fixed: "right",
                    dataIndex: "status",
                    hideInSearch: true,
                    render: (_, row) => (
                      <Button
                        type="link"
                        onClick={() => {
                          form.setFieldValue(
                            "pointUrl",
                            row.userId + "-" + row.nickName
                          );
                          setVisible(false);
                        }}
                      >
                        选择
                      </Button>
                    ),
                  },
                ]
          }
        />
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
